package com.oauth2.demo.config.service;

import com.oauth2.demo.dao.OauthClientDetailsDao;
import com.oauth2.demo.mapper.entity.OauthClientDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2019/9/6.
 */
@Slf4j
@Configuration
public class OauthClientDetailsServiceImpl implements ClientDetailsService{

    @Autowired
    private OauthClientDetailsDao oauthClientDetailsDao;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    /**
     * 根据id client_id获取客户端信息
     * @param s
     * @return
     * @throws ClientRegistrationException
     */
    public ClientDetails loadClientByClientId(String s) throws ClientRegistrationException {
        // 根据Id查询
        OauthClientDetails oauthClientDetails = oauthClientDetailsDao.selectByPrimaryKey(s);
        try {
            return translateClient(oauthClientDetails);
        } catch (Exception e) {
            log.error("===> {}", e);
            throw new ClientRegistrationException("无效client");
        }
    }

    public ClientDetails translateClient(OauthClientDetails details) {
        BaseClientDetails clientDetails = new BaseClientDetails(details.getClientId(), details.getResourceIds(), details.getScope(),
                details.getAuthorizedGrantTypes(), details.getAuthorities(), details.getWebServerRedirectUri());
        clientDetails.setClientSecret(details.getClientSecret());
        clientDetails.setScope(StringUtils.commaDelimitedListToSet(details.getScope()));
        clientDetails.setAutoApproveScopes(StringUtils.commaDelimitedListToSet(details.getAutoapprove()));
        clientDetails.setRefreshTokenValiditySeconds(details.getRefreshTokenValidity());
        clientDetails.setAccessTokenValiditySeconds(details.getAccessTokenValidity());
        clientDetails.setClientSecret(passwordEncoder.encode(clientDetails.getClientSecret()));
        return clientDetails;
    }
}
